<template>
  <div class="host-type-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>主机类型管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加类型
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="类型名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入类型名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="启用" value="enabled" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 类型表格 -->
      <el-table
        :data="typeList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="类型名称" min-width="150" />
        <el-table-column prop="code" label="类型代码" width="120" />
        <el-table-column prop="icon" label="图标" width="80">
          <template #default="{ row }">
            <el-icon :size="20">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="100">
          <template #default="{ row }">
            <div class="color-preview" :style="{ backgroundColor: row.color }"></div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'enabled' ? 'success' : 'danger'">
              {{ row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hostCount" label="主机数量" width="100" />
        <el-table-column prop="specs" label="规格配置" min-width="200">
          <template #default="{ row }">
            <div class="specs-info">
              <span>CPU: {{ row.specs.cpu }}核</span>
              <span>内存: {{ row.specs.memory }}GB</span>
              <span>磁盘: {{ row.specs.disk }}GB</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 'enabled' ? 'danger' : 'success'"
              size="small"
              @click="toggleStatus(row)"
            >
              {{ row.status === 'enabled' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :disabled="row.hostCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑类型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="类型名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入类型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型代码" prop="code">
              <el-input v-model="form.code" placeholder="请输入类型代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-select v-model="form.icon" placeholder="请选择图标" style="width: 100%">
                <el-option label="服务器" value="Monitor">
                  <el-icon><Monitor /></el-icon>
                  服务器
                </el-option>
                <el-option label="云服务器" value="CloudServer">
                  <el-icon><Monitor /></el-icon>
                  云服务器
                </el-option>
                <el-option label="物理机" value="Cpu">
                  <el-icon><Cpu /></el-icon>
                  物理机
                </el-option>
                <el-option label="虚拟机" value="Box">
                  <el-icon><Box /></el-icon>
                  虚拟机
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-color-picker v-model="form.color" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 规格配置 -->
        <el-form-item label="规格配置">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="CPU(核)" prop="specs.cpu">
                <el-input-number v-model="form.specs.cpu" :min="1" :max="128" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="内存(GB)" prop="specs.memory">
                <el-input-number v-model="form.specs.memory" :min="1" :max="1024" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="磁盘(GB)" prop="specs.disk">
                <el-input-number v-model="form.specs.disk" :min="10" :max="10240" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="enabled">启用</el-radio>
            <el-radio value="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入类型描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Monitor,
  Cpu,
  Box
} from '@element-plus/icons-vue'

// 注册图标组件
const iconComponents = {
  Plus,
  Search,
  Monitor,
  Cpu,
  Box
}

// 接口定义
interface HostType {
  id: string
  name: string
  code: string
  icon: string
  color: string
  status: string
  hostCount: number
  specs: {
    cpu: number
    memory: number
    disk: number
  }
  description: string
  createTime: string
}

interface SearchForm {
  name: string
  status: string
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加类型')
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 类型列表
const typeList = ref<HostType[]>([])

// 表单数据
const form = reactive<HostType>({
  id: '',
  name: '',
  code: '',
  icon: '',
  color: '#409eff',
  status: 'enabled',
  hostCount: 0,
  specs: {
    cpu: 2,
    memory: 4,
    disk: 100
  },
  description: '',
  createTime: ''
})

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入类型代码', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: '类型代码必须以字母开头，只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 模拟数据
const mockData: HostType[] = [
  {
    id: 'HT001',
    name: '云服务器',
    code: 'cloud_server',
    icon: 'Monitor',
    color: '#409eff',
    status: 'enabled',
    hostCount: 15,
    specs: { cpu: 4, memory: 8, disk: 200 },
    description: '云端虚拟服务器，弹性可扩展',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 'HT002',
    name: '物理服务器',
    code: 'physical_server',
    icon: 'Cpu',
    color: '#67c23a',
    status: 'enabled',
    hostCount: 8,
    specs: { cpu: 16, memory: 64, disk: 1000 },
    description: '高性能物理服务器',
    createTime: '2024-01-10 14:20:00'
  },
  {
    id: 'HT003',
    name: '容器主机',
    code: 'container_host',
    icon: 'Box',
    color: '#e6a23c',
    status: 'enabled',
    hostCount: 25,
    specs: { cpu: 2, memory: 4, disk: 50 },
    description: '容器化部署主机',
    createTime: '2024-01-08 09:15:00'
  }
]

// 获取类型列表
const fetchTypeList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 应用搜索过滤
    let filteredData = [...mockData]
    if (searchForm.name) {
      filteredData = filteredData.filter(item =>
        item.name.includes(searchForm.name) || item.code.includes(searchForm.name)
      )
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }

    pagination.total = filteredData.length
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    typeList.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取类型列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTypeList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: ''
  })
  pagination.currentPage = 1
  fetchTypeList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchTypeList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchTypeList()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加类型'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: HostType) => {
  dialogTitle.value = '编辑类型'
  isEdit.value = true
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: '',
    name: '',
    code: '',
    icon: '',
    color: '#409eff',
    status: 'enabled',
    hostCount: 0,
    specs: {
      cpu: 2,
      memory: 4,
      disk: 100
    },
    description: '',
    createTime: ''
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
        dialogVisible.value = false
        fetchTypeList()
      } catch (error) {
        ElMessage.error(`${isEdit.value ? '更新' : '创建'}失败`)
      }
    }
  })
}

// 切换状态
const toggleStatus = async (row: HostType) => {
  try {
    const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
    const action = newStatus === 'enabled' ? '启用' : '禁用'

    await ElMessageBox.confirm(
      `确定要${action}类型 "${row.name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    row.status = newStatus
    ElMessage.success(`${action}成功`)
  } catch (error) {
    // 用户取消操作
  }
}

// 删除类型
const handleDelete = async (row: HostType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除类型 "${row.name}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    ElMessage.success('删除成功')
    fetchTypeList()
  } catch (error) {
    // 用户取消操作
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTypeList()
})
</script>

<style scoped>
.host-type-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(120, 220, 255, 0.1);
}

.color-preview {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.specs-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.specs-info span {
  font-size: 12px;
  color: var(--tech-text-secondary);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
